import 'dart:async';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:C20Driver/provider/record_provider.dart';
import 'package:C20Driver/service/mqtt_manage.dart';
import 'package:C20Driver/service/request.dart';
import 'package:path_provider/path_provider.dart';
import 'package:intl/intl.dart' show DateFormat;
import 'package:provider/provider.dart';

class Record {
  StreamSubscription _recorderSubscription;

  FlutterSound flutterSound;
  RecordProvider recordProvider = new RecordProvider();
  bool _isRecording = false;
  String path;
  var clientId;

  Record() {
    flutterSound = new FlutterSound();
    flutterSound.setSubscriptionDuration(0.01);
    flutterSound.setDbPeakLevelUpdate(0.8);
    flutterSound.setDbLevelEnabled(true);
    clientId = MqttManage.getInstance().getClientId;
  }

  void stopRecorder() async {
    try {
      String result = await flutterSound.stopRecorder();
      if (_recorderSubscription != null) {
        _recorderSubscription.cancel();
        _recorderSubscription = null;
      }
      Request.genUptoken(clientId: clientId, defaultFix: "aac").then((value) {
        print("value${value}");
        if (value != null) {
          List dates = value['tokenList'] as List;
          var key = dates.first["resourceKey"];
          var upLoadToken = dates.first["token"];
          print("value key${key}");
          print("value upLoadToken${upLoadToken}");
          Request.qiniuUpload(key: key, uploadToken: upLoadToken, file: path)
              .then((value) {
            if (value != null) {
              ////data/user/0/com.maitianshanglv.driver.andorid/app_flutter/1486044305117216256_1616575805938.aac
              print("valuesss2222${value}");
              print("valuesss2${path}");

              String orderId = path.substring(59, 78);
              String time = path.substring(79, 92);
              String url = value["url"];
              Request.submitRecordUrl(url, orderId, time).then((value) {
                if (value != null) {
                  getApplicationDocumentsDirectory().then((value) {
                    print("value  dele${value}");
                    deleteFiles(value.path);
                  });
                }
              });
            }
          });
        }
      });
    } catch (err) {
      print('stopRecorder error: $err');
    }
  }

  void startRecorder({BuildContext context, String orderId}) async {
    try {
      Directory appDocDir = await getApplicationDocumentsDirectory();
      String filePath = appDocDir.path + "/";
      print("filePath===$filePath");
      path = await flutterSound.startRecorder(
          uri: "$filePath${orderId}_${currentTimeMillis()}.aac");
      print('startRecorder: $path');
      _recorderSubscription = flutterSound.onRecorderStateChanged.listen((e) {
        DateTime date =
            new DateTime.fromMillisecondsSinceEpoch(e.currentPosition.toInt());
        String txt = DateFormat('mm:ss:SS', 'en_US').format(date);
        //  recordProvider.recordTimeListen(txt.substring(0, 8));
        // this.setState(() {
        //   this._recorderTxt = txt.substring(0, 8);
        // });
      });

      // this.setState(() {
      //   this._isRecording = true;
      // });
    } catch (err) {
      print('startRecorder error: $err');
    }
  }

  List<File> printFiles(String path) {
    List<File> aacFiles = new List();
    try {
      var dir = new Directory(path);
      List<FileSystemEntity> files = dir.listSync();
      for (var f in files) {
        if (f.path.endsWith("aac")) {
          print("f.path${f.path}");
          aacFiles.add(f);
          // f.deleteSync();
        }
      }
      return aacFiles;
    } catch (e) {
      print("目录不存在！");
      return aacFiles;
    }
  }

  void deleteFiles(String path) {
    try {
      var dir = new Directory(path);
      List<FileSystemEntity> files = dir.listSync();
      for (var f in files) {
        if (f.path.endsWith("aac")) {
          print("f.path${f.path}");
          File file = new File(f.path);
          int aacSize = file.lengthSync();
          if (aacSize >= 0) {
            f.deleteSync();
          }
        }
      }
    } catch (e) {
      print("删除目录夹不存在！");
    }
  }

  int currentTimeMillis() {
    return new DateTime.now().millisecondsSinceEpoch;
  }
}
